import java.util.*;

public class ZigzagLevelOrder {

    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        if (root == null) return Collections.EMPTY_LIST;
        HashMap<TreeNode, Integer> maps = new HashMap<>();
        int curLevel = 1;
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        maps.put(root, 1);
        List<Integer> list = new ArrayList<>();
        List<List<Integer>> ans = new ArrayList<>();
        boolean flag = true;
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            Integer nodeLevel = maps.get(node);
            if (curLevel != nodeLevel) {
                curLevel++;
                if (flag) {
                    ans.add(new ArrayList<>(list));
                } else {
                    Collections.reverse(list);
                    ans.add(new ArrayList<>(list));
                }
                flag = !flag;
                list.clear();
            }
            list.add(node.val);
            if (node.left != null) {
                queue.add(node.left);
                maps.put(node.left, curLevel + 1);
            }
            if (node.right != null) {
                queue.add(node.right);
                maps.put(node.right, curLevel + 1);
            }
        }
        if (flag) {
            ans.add(new ArrayList<>(list));
        } else {
            Collections.reverse(list);
            ans.add(new ArrayList<>(list));
        }
        return ans;
    }
}
